package com.ijava.base.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ijava.base.dao.RoleDAO;
import com.ijava.base.domain.Role;
import com.ijava.base.service.RoleService;

public class RoleServiceImpl implements RoleService {
	private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);
	private RoleDAO dao;

	public RoleDAO getDao() {
		return dao;
	}

	public void setDao(RoleDAO dao) {
		this.dao = dao;
	}

	public void remove(String id) throws Exception {
		dao.remove(id);
	}

	public void mutilRemove(Role role) throws Exception {
		try {
			String[] keys = role.getKeys();
			if(null == keys)
				return;
			for (int i = 0; i < keys.length; i++) {
				remove(keys[i]);
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public void save(Role role) throws Exception {
		dao.save(role);
	}

	public void update(Role role) throws Exception {
		dao.update(role);
	}

	public void saveOrUpdate(Role role) throws Exception {
		dao.saveOrUpdate(role);
	}

	public Role get(String id) throws Exception {
		return dao.get(id);
	}

	public List findWithPaging(Role role) throws Exception {
		try {
			int firstRow = (role.getPageNo() - 1) * role.getPageSize();
			int maxRow = role.getPageSize();

			List paramList = new ArrayList();
			StringBuffer condition = new StringBuffer(" where 1 = 1 ");
			if (StringUtils.hasLength(role.getRoleCode())) {
				condition.append(" and roleCode like ?");
				paramList.add("%" + role.getRoleCode() + "%");
			}
			if (StringUtils.hasLength(role.getRoleName())) {
				condition.append(" and roleName like ?");
				paramList.add("%" + role.getRoleName() + "%");
			}
			if (StringUtils.hasLength(String.valueOf(role.getRowEnable()))) {
				condition.append(" and rowEnable = ?");
				paramList.add(role.getRowEnable());
			}

			int total = dao.find(
					"select count(*) from " + Role.class.getName()
							+ condition.toString(), paramList).size();
			role.setTotal(total);

			String queryString = "from " + Role.class.getName()
					+ condition.toString();
			return dao.findWithPaging(queryString, paramList, firstRow, maxRow);
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

}
